package com.mm.cloth.utils;

import android.content.Context;
import android.util.Log;

import com.mm.cloth.api.ApiClient;
import com.mm.cloth.api.ApiService;
import com.mm.cloth.model.Category;
import com.mm.cloth.model.response.ApiResponse;
import com.mm.cloth.model.response.ClothesListResponse;
import com.mm.cloth.model.response.SystemConfigResponse;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * API测试辅助工具
 * 用于测试token认证机制是否正常工作
 */
public class ApiTestHelper {
    
    private static final String TAG = "ApiTestHelper";
    
    /**
     * 测试公开接口（不需要token）
     */
    public static void testPublicEndpoints() {
        Log.d(TAG, "=== 测试公开接口 ===");
        
        ApiService apiService = ApiClient.getInstance().getApiService();
        
        // 测试系统配置接口
        apiService.getSystemConfig().enqueue(new Callback<ApiResponse<SystemConfigResponse>>() {
            @Override
            public void onResponse(Call<ApiResponse<SystemConfigResponse>> call, Response<ApiResponse<SystemConfigResponse>> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, "✅ 系统配置接口调用成功（无需token）");
                } else {
                    Log.e(TAG, "❌ 系统配置接口调用失败: " + response.code());
                }
            }
            
            @Override
            public void onFailure(Call<ApiResponse<SystemConfigResponse>> call, Throwable t) {
                Log.e(TAG, "❌ 系统配置接口网络错误: " + t.getMessage());
            }
        });
    }
    
    /**
     * 测试需要token的接口
     */
    public static void testAuthenticatedEndpoints(Context context) {
        Log.d(TAG, "=== 测试需要token的接口 ===");
        
        // 检查token状态
        String token = TokenManager.getToken(context);
        if (token == null) {
            Log.w(TAG, "⚠️ 未找到有效token，需要token的接口可能会失败");
        } else {
            Log.d(TAG, "✅ 找到有效token: " + token.substring(0, Math.min(10, token.length())) + "...");
        }
        
        ApiService apiService = ApiClient.getInstance().getApiService();
        
        // 测试分类列表接口
        apiService.getCategoryList().enqueue(new Callback<ApiResponse<List<Category>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<Category>>> call, Response<ApiResponse<List<Category>>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<List<Category>> apiResponse = response.body();
                    if (apiResponse.getCode() == 200) {
                        Log.d(TAG, "✅ 分类列表接口调用成功（需要token）");
                        List<Category> categories = apiResponse.getData();
                        if (categories != null) {
                            Log.d(TAG, "   获取到 " + categories.size() + " 个分类");
                        }
                    } else {
                        Log.e(TAG, "❌ 分类列表接口返回错误: " + apiResponse.getCode() + " - " + apiResponse.getMessage());
                    }
                } else {
                    Log.e(TAG, "❌ 分类列表接口调用失败: " + response.code());
                    if (response.code() == 401) {
                        Log.e(TAG, "   可能是token无效或已过期");
                    }
                }
            }
            
            @Override
            public void onFailure(Call<ApiResponse<List<Category>>> call, Throwable t) {
                Log.e(TAG, "❌ 分类列表接口网络错误: " + t.getMessage());
            }
        });
        
        // 测试衣物列表接口
        apiService.getClothesList(1, 10, null, null, null).enqueue(new Callback<ApiResponse<ClothesListResponse>>() {
            @Override
            public void onResponse(Call<ApiResponse<ClothesListResponse>> call, Response<ApiResponse<ClothesListResponse>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<ClothesListResponse> apiResponse = response.body();
                    if (apiResponse.getCode() == 200) {
                        Log.d(TAG, "✅ 衣物列表接口调用成功（需要token）");
                        ClothesListResponse data = apiResponse.getData();
                        if (data != null && data.getList() != null) {
                            Log.d(TAG, "   获取到 " + data.getList().size() + " 件衣物");
                        }
                    } else {
                        Log.e(TAG, "❌ 衣物列表接口返回错误: " + apiResponse.getCode() + " - " + apiResponse.getMessage());
                    }
                } else {
                    Log.e(TAG, "❌ 衣物列表接口调用失败: " + response.code());
                    if (response.code() == 401) {
                        Log.e(TAG, "   可能是token无效或已过期");
                    }
                }
            }
            
            @Override
            public void onFailure(Call<ApiResponse<ClothesListResponse>> call, Throwable t) {
                Log.e(TAG, "❌ 衣物列表接口网络错误: " + t.getMessage());
            }
        });
    }
    
    /**
     * 完整的API认证测试
     */
    public static void runFullAuthTest(Context context) {
        Log.d(TAG, "==========================================");
        Log.d(TAG, "开始完整的API认证机制测试");
        Log.d(TAG, "==========================================");
        
        // 检查登录状态
        boolean isLoggedIn = TokenManager.isLoggedIn(context);
        Log.d(TAG, "当前登录状态: " + (isLoggedIn ? "已登录" : "未登录"));
        
        if (isLoggedIn) {
            Log.d(TAG, "用户已登录，token有效");
        }
        
        // 测试公开接口
        testPublicEndpoints();
        
        // 延迟测试需要认证的接口，避免请求冲突
        new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(() -> {
            testAuthenticatedEndpoints(context);
        }, 2000);
    }
}
